<template>
  <div class="app-container calendar-list-container" style="margin: 10px">
    <el-form :inline="true" :model="queryDataForm" @keyup.enter.native="getList()"  class="company-wrapper_search" @submit.native.prevent>
      <el-form-item label="角色名称">
        <el-input v-model="queryDataForm.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getList('noPage')"  type="primary">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button class="mtb15" @click="add" type="primary">新增角色</el-button>
    <NbTable
      :tableHeaders="tableHeaders"
      :tableData="tableData"
      :clickData="clickData"
      operatorFixed="left"
      operatorText
      height="auto"
      @clickRight="clickRight"
      :align="align"
      :headerMap="queryMap"
    />
    <el-dialog title="查询权限" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form
        :inline="false"
        :model="resetDataForm"
        class="demo-form-inline"
        ref="ruleResetPwdForm"
      >
        <el-form-item size="mini" label="授权">
          <el-tree
            ref="menuListTree"
            :data="data2"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item style="text-align:right">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmPermission">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination
      align="right"
      style="padding-top: 20px;margin-bottom:100px;"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="queryDataForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryDataForm.size"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
import NbTable from '../../../components/nb-table'
export default {
  name: 'promotion',
  components: {
    NbTable
  },
  data () {
    return {
      clickData: [],
      align: 'center',
      tableHeaders: [
        { headerKey: 'name', headerName: '角色名称' },
        { headerKey: 'description', headerName: '角色描述' },
        { headerKey: 'remark', headerName: '备注' }
        // { headerKey: 'isEffect', headerName: '是否有效' }
      ],
      queryMap: [
        {
          headerKey: 'isEffect',
          headerName: '是否有效',
          fun (row) {
            if (row.isEffect) {
              return '有效'
            } else if (!row.isEffect) {
              return '无效'
            } else {
              return '-'
            }
          }
        }
      ],
      queryDataForm: {
        name: '',
        page: 1,
        size: 10
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      data2: [],
      nodes: [],
      isShowError: false,
      dialogVisible: false,
      tableData: [],
      totalPage: 200,
      pageSize: 10,
      pageIndex: 1,
      listLoading: false,
      resetDataForm: {
        donePwd: '',
        pwd: ''
      },
      code: ''
    }
  },
  mounted: function () {
    this.getList()
    this.clickData = this.$showBtn([
      { btnName: 'ROLE_EDIT', name: '编辑', type: 'edit' },
      { btnName: 'SHAGRO_DEL', name: '删除', type: 'delete' }
    ])
    // document.onkeydown = e => {
    //   var key = window.event.keyCode
    //   if (key == 13) {
    //     this.getList(1)
    //   }
    // }
  },
  methods: {
    onReset () {
      this.queryDataForm.name = ''
      this.getList('noPage')
    },
    lookPermission (code) {
      this.dialogVisible = true
      this.code = code
      this.nodes = []
      this.$http
        .post(`/${this.$const.PREFIX.AUTHORITY}/role/findPermissionOfRole`, {
          roleCode: code
        })
        .then(res => {
          this.data2 = this.treeDataTranslate(res.data, 'code')
          console.log('data2', this.data2)
          this.getNodes(this.data2)
          console.log('nodes', this.nodes)
          this.$refs.menuListTree.setCheckedKeys(this.nodes)
        })
    },
    clickRight (data) {
      if (data.type === 'edit') {
        this.edit(data.row)
      } else if (data.type === 'delete') {
        this.delUser(data.row.code)
      } else if (data.type === 'look') {
        this.lookPermission(data.row.code)
      }
    },
    treeDataTranslate (data, id = 'code', pid = 'parentCode') {
      var res = []
      var temp = {}
      for (var i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i]
      }
      for (var k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
          if (!temp[data[k][pid]]['children']) {
            temp[data[k][pid]]['children'] = []
          }
          if (!temp[data[k][pid]]['level']) {
            temp[data[k][pid]]['level'] = 1
          }
          data[k]['level'] = temp[data[k][pid]].level + 1
          temp[data[k][pid]]['children'].push(data[k])
        } else {
          res.push(data[k])
        }
      }
      return res
    },
    // 递归获取节点
    getNodes (treenodes) {
      if (treenodes.length > 0) {
        for (var i = 0; i < treenodes.length; i++) {
          if (treenodes[i].children) {
            this.getNodes(treenodes[i].children)
          } else {
            if (treenodes[i].selected) {
              this.nodes.push(treenodes[i].id)
            }
          }
        }
      }
    },
    confirmPermission () {
      let keyList = this.$refs.menuListTree.getCheckedNodes()
      let halfKeyList = this.$refs.menuListTree.getHalfCheckedNodes()
      let result = keyList.concat(halfKeyList).map(item => item.code)
      let param = {
        roleCode: this.code,
        permissionCodes: result
      }
      console.log('param: ', param)
      this.$http
        .post(`/${this.$const.PREFIX.AUTHORITY}/role/givePermissions`, param)
        .then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogVisible = false
        })
    },
    add () {
      this.$router.push('/systemSettings/role/addRole')
    },
    edit (row) {
      this.$router.push({
        path: '/systemSettings/role/edit',
        query: { code: row.code }
      })
    },
    delUser (row) {
      this.$confirm('确认删除该条数据？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/${this.$const.PREFIX.AUTHORITY}/role/dels`, { codes: [row] })
          .then(res => {
            if (res.result) {
              this.queryDataForm.page = 1
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.getList()
            } else {
              this.$message.error({
                message: res.msg,
                duration: 5000
              })
            }
          })
      })
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    getList (type) {
      this.queryDataForm.name = this.queryDataForm.name.trim()
      if (type && type === 'noPage') {
        this.queryDataForm.page = 1
      }
      this.$http
        .post(
          `/${this.$const.PREFIX.AUTHORITY}/role/findTRoleByConditons`,
          this.queryDataForm
        )
        .then(res => {
          var backData = res.data

          if (res.result) {
            this.totalPage = backData.total
            this.tableData = backData.records
          } else {
            this.$message.error({
              message: res.msg,
              duration: 5000
            })
          }
        })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.queryDataForm.size = val
      this.queryDataForm.page = 1
      this.getList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.queryDataForm.page = val
      this.getList()
    },
    delQueryModel () {}
  }
}
</script>
